<template>
  <div id="editor">
    <!-- 组件方式 -->
    <!-- <ToastUIEditor
      ref="editorRef"
      :initialValue="editorText"
      height="500px"
      :options="editorOptions"
      @change="onChange"
    /> -->
    
    <!-- 或通过容器渲染 -->
    <div ref="editorContainer"></div>
  </div>
</template>

<script>
// Vue 3 引入
import { Editor } from '@toast-ui/editor';
import '@toast-ui/editor/dist/toastui-editor.css';
// import { Editor as ToastUIEditor } from '@toast-ui/editor-vue3';
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight';
// import Editor, { codeSyntaxHighlight } from '@toast-ui/editor';

// import hljs from 'highlight.js';
// import 'highlight.js/styles/atom-one-dark.min.css';

import Prism from 'prismjs';
import 'prismjs/themes/prism.css';

import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-java';
import 'prismjs/components/prism-python';
import 'prismjs/components/prism-c';
import 'prismjs/components/prism-cpp';

import uml from '@toast-ui/editor-plugin-uml';

const prismLanguages = {
  csharp: () => import('prismjs/components/prism-csharp'),
  go: () => import('prismjs/components/prism-go'),
  swift: () => import('prismjs/components/prism-swift'),
  dart: () => import('prismjs/components/prism-dart'),
  nginx: () => import('prismjs/components/prism-nginx'),
  bash: () => import('prismjs/components/prism-bash'),
  sql: () => import('prismjs/components/prism-sql'),
  typescript: () => import('prismjs/components/prism-typescript'),
  css: () => import('prismjs/components/prism-css'),
  html: () => import('prismjs/components/prism-markup'),
  xml: () => import('prismjs/components/prism-markup'),
  json: () => import('prismjs/components/prism-json'),
  yaml: () => import('prismjs/components/prism-yaml'),
  ruby: () => import('prismjs/components/prism-ruby'),
  php: () => import('prismjs/components/prism-php'),
  kotlin: () => import('prismjs/components/prism-kotlin'),
  scala: () => import('prismjs/components/prism-scala'),
  rust: () => import('prismjs/components/prism-rust'),
  r: () => import('prismjs/components/prism-r'),
  perl: () => import('prismjs/components/prism-perl'),
  lua: () => import('prismjs/components/prism-lua'),
  powershell: () => import('prismjs/components/prism-powershell'),
  docker: () => import('prismjs/components/prism-docker'),
  graphql: () => import('prismjs/components/prism-graphql'),
  markdown: () => import('prismjs/components/prism-markdown'),
  mermaid: () => import('prismjs/components/prism-mermaid')
};

const language = 'nginx'; // 这是你的动态语言字符串

function loadPrismLanguage(lang) {
  if (!prismLanguages[lang]) {
    return Promise.reject(new Error(`Unsupported language: ${lang}`));
  }
  
  return prismLanguages[lang]()
    .then(() => {
      console.log(`${lang} language loaded`);
      return true;
    })
    .catch(error => {
      console.error(`Failed to load ${lang} language:`, error);
      throw error;
    });
}

import mdkatex from 'katex';

const pluginOptions = function(editor){
  console.log(editor)
  return "asdas "
};

// function latexPlugin() {
//   const toHTMLRenderers = {
//     latex(node) {
//       const generator = new latexjs.HtmlGenerator({ hyphenate: false });
//       const { body } = latexjs.parse(node.literal, { generator }).htmlDocument();

//       return [
//         { type: 'openTag', tagName: 'div', outerNewLine: true },
//         { type: 'html', content: body.innerHTML },
//         { type: 'closeTag', tagName: 'div', outerNewLine: true }
//       ];
//     },
//   }

//   return { toHTMLRenderers }
// }


export default {
  components: {
    
  },
  data() {
    return {
      editorText: `# 欢迎使用 Markdown 编辑器

这是一个功能强大的编辑器，支持各种 Markdown 语法。

## 主要特性

- **所见即所得** - 实时预览编辑效果
- **代码高亮** - 支持多种编程语言
- **表格支持** - 轻松创建数据表格
- **LaTeX 公式** - 支持数学公式编辑
- **Mermaid 图表** - 创建流程图和序列图

## 代码示例

\`\`\`javascript
// JavaScript 示例
function greet(name) {
    console.log(\`Hello, \${name}!\`);
}

greet('Markdown 用户');
\`\`\`


\`\`\`python
def greet(name):
    print(f"Hello, {name}!")
greet("Markdown 用户")
\`\`\`
\`\`\`c
#include <stdio.h>
int main() {
    printf("Hello, World!");
    return 0;
}  
\`\`\`
\`\`\`go
package main
import "fmt"
func main() {
    fmt.Println("Hello, World!")
}
\`\`\`
\`\`\`shell
echo "Hello, World!"
\`\`\`
\`\`\`dart
void main() {
    print('Hello, World!');
}
\`\`\`
\`\`\`nginx
server {
    listen 80;
    server_name example.com;    
    location / {
        proxy_pass URL_ADDRESS        proxy_pass http://backend;
    }
}
\`\`\`

## 数学公式示例

$$
\\int_0^\\infty x^2 dx
$$

## 表格示例

| 功能         | 是否支持 | 说明         |
|--------------|----------|--------------|
| 图片上传     | ✓        | 支持拖放上传 |
| 深色模式     | ✓        | 夜间友好     |
| 导出 HTML    | ✓        | 完整格式保留 |
| 版本历史     | ✓        | 自动保存记录 |

## Mermaid 流程图

\`\`\`mermaid
graph TD;
    A[开始] --> B(编辑内容);
    B --> C{是否满意?};
    C -->|是| D[保存内容];
    C -->|否| B;
    D --> E[完成];
\`\`\`
`,
      editorOptions: {
        language: 'zh-CN',        // 中文
		    height:'500px',
        initialEditType: 'markdown', // 或 'wysiwyg'
        previewStyle: 'vertical',    // 或 'tab'
        hideModeSwitch: true,        // 隐藏模式切换按钮
        viewer: false,
        usageStatistics: false,
        useCommandShortcut: true,
        // toolbarItems: [              // 自定义工具栏
        //   ['heading', 'bold', 'italic'],
        //   ['ul', 'ol', 'task'],
        //   ['table', 'image', 'link']
        // ],
        hooks: {
                addImageBlobHook: (blob, callback) => {
                    // 这里可以添加图片上传逻辑
                    const reader = new FileReader();
                    reader.onload = function() {
                      callback(reader.result, '图片描述');
                        // callback("https://图片地址", '图片上传逻辑');
                    };
                    reader.readAsDataURL(blob);
                }
            }
      },
      loadLanguages:  []
    };
  },
  mounted() {
    // 容器渲染方式（可选）
    this.initEditor();
  },
  methods: {
    // 监听内容变化
    onChange() {
      const content = this.$refs.editorRef.getInstance().getMarkdown();
      console.log('当前内容:', content);
    },
    initLanguage() {
      // 提取所有代码块语言
      const codeBlocks = this.editorText.match(/```(\w+)[\s\S]*?```/g) || [];
        this.loadLanguages = [...new Set(codeBlocks.map(block => {
          const match = block.match(/```(\w+)/);
          return match ? match[1] : null;
        }).filter(Boolean))];
        console.log('检测到的语言:', this.loadLanguages);
        // 动态加载所有需要的语言插件
        Promise.all(this.loadLanguages.map(lang => {
          if (prismLanguages[lang]) {
            return prismLanguages[lang]();
          }
          return Promise.resolve();
        })).then(() => {
          // 触发语法高亮更新
          Prism.highlightAll();
        }).catch(error => {
          console.error('加载语言插件失败:', error);
        });
    },
    
    // 容器渲染初始化
    async initEditor() {
      this.initLanguage();
      // 初始化编辑器实例，使用容器作为挂载点
      // 确保 this.editorOptions 包含所有需要的选项，包括 plugin
      this.editor = new Editor({
        el: this.$refs.editorContainer,
        ...this.editorOptions,
        initialValue: this.editorText,
        plugins: [[codeSyntaxHighlight, { highlighter: Prism }],[uml, {}], [pluginOptions, {}]],
      });
      this.editor.on('change', () => {
        const markdown = this.editor.getMarkdown();
        console.log('内容变化:', markdown);

        const html =  this.editor.getHTML()
        console.log('html:', html);
        
        // 提取所有代码块语言
        const codeBlocks = markdown.match(/```(\w+)[\s\S]*?```/g) || [];
        codeBlocks.forEach(block => {
          const match = block.match(/```(\w+)/);
          if (match) {
            const lang = match[1];
            if (prismLanguages[lang] && !this.loadLanguages.includes(lang)) {
              this.loadLanguages.push(lang)
              loadPrismLanguage(lang)
            }

          }
        });
      });
    },
    
    // 获取内容（示例）
    getContent() {
      return this.$refs.editorRef.getInstance().getMarkdown();
    },
    
    // 设置内容（示例）
    setContent(text) {
      this.$refs.editorRef.getInstance().setMarkdown(text);
    }
  },
  beforeUnmount() {
    // 容器渲染时销毁实例
    // if (this.editor) this.editor.destroy();
  }
};
</script>